﻿using GameLibrary.Internal;
using G.Model;
using G.Model.Runtime.Converters;
using System.Collections.Generic;
using System.ComponentModel;
using G.Runtime;

namespace G.Runtime
{
    public class TurnEventArgs
    {
        public GameElement[] elements;
        public bool handled;
    }
    
    public class GamePlayer : 
        System.IComparable<GamePlayer>,
        HasValues, HasGameSpace
    {
        public delegate void TurnHandler(TurnEventArgs args);
        public event TurnHandler TurnEvent;
        
        private readonly GameSpace _Game;
        private readonly GamePlayerDef _PlayerDef;
        private readonly GameValues _GameValues;
        private readonly List<GameElement> _OwnedElements = new List<GameElement>();

        public GamePlayer(GamePlayerDef pPlayerDef, GameSpace pGame)
        {
            _PlayerDef = pPlayerDef;
            _Game = pGame;
            _GameValues = new CalcGameValues(
                _Game.Def.GlobalDef.GamePlayerValueDefs, 
                pGame, this);
        }

        public GamePlayerDef Def
        {
            get { return _PlayerDef; }
        }

        public GameSpace Game
        {
            get { return _Game; }
        }

        public string Name
        {
            get { return _PlayerDef.Name; }
        }

        public System.Drawing.Color Color
        {
            get { return _PlayerDef.Color; }
        }

        public List<GameElement> OwnedElements
        {
            get { return _OwnedElements; }
        }

        public GameValues GameValues
        {
            get { return _GameValues; }
        }

        private GameElement[] GetElements()
        {
            List<GameElement> list = new List<GameElement>();
            foreach (GameElement e in _Game.Elements)
            {
                if (e.Player == this.Name)
                {
                    list.Add(e);
                }
            }
            return list.ToArray();
        }

        public int CompareTo(GamePlayer other)
        {
            return _PlayerDef.Name.CompareTo(other._PlayerDef.Name);
        }

        public override string ToString()
        {
            return _PlayerDef.Name;
        }

        public void FireOnTurn(List<GameElement> elements)
        {
            if (TurnEvent != null)
            {
                TurnEventArgs args = new TurnEventArgs();
                args.elements = elements.ToArray();
                TurnEvent(args);
            }
        }

    }
}
